package com.jovision.sovplay;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.BaseActivity;
import com.aviccxzx.smarthome.entity.StreamFile;
import com.jovision.AppConsts;
import com.jovision.JVNetConst;
import com.jovision.JniUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;

public class JVRemoteListActivity extends BaseActivity {

    private final String TAG = "JVRemoteListActivity";
    public static final int FLAG_DOWNLOAD_FILE = 0x01111;//录像下载

    // intent 参数
    private int window;// 窗口

    // view
    private EditText selectDateET;// 选择的日期
    private ImageView moreDataIV;// 下三角
    private StreamRemoteVideoAdapter remoteVideoAdapter;
    private ListView remoteLV;
    private TextView downloadProTV;//下载进度

    //variable
    private Calendar rightNow = Calendar.getInstance();
    private ArrayList<StreamFile> videoList;
    private int year;
    private int month;
    private int day;
    private int hasDownLoadSize = 0;// 已下载文件大小
    private int downLoadFileSize = 0;// 下载文件大小
    /**
     * 日历轻触事件
     */
    OnTouchListener onTouchListener = new OnTouchListener() {
        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            if (MotionEvent.ACTION_DOWN == arg1.getAction()) {
                new DatePickerDialog(JVRemoteListActivity.this,
                        new DatePickerDialog.OnDateSetListener() {

                            public void onDateSet(DatePicker arg0, int year,
                                                  int month, int day) {
                                selectDateET.setText(String.format(AppConsts.FORMAT_DATE, year, ++month, day));
                                searchRemoteData();
                            }
                        }, rightNow.get(Calendar.YEAR),
                        rightNow.get(Calendar.MONTH),
                        rightNow.get(Calendar.DAY_OF_MONTH)).show();
            }
            return true;
        }

    };

    /**
     * 远程回放列点击播放事件
     */
    OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {

            StreamFile videoFile = videoList.get(arg2);
            String acBuffStr = videoFile.getFilePath();
            Log.v(TAG, "onItemClickListener--acBuffStr:" + acBuffStr);

            if (null != acBuffStr && !"".equalsIgnoreCase(acBuffStr)) {
                Intent intent = new Intent();
                intent.setClass(JVRemoteListActivity.this,
                        JVRemotePlayBackActivity.class);
                intent.putExtra("window", window);
                intent.putExtra("acBuffStr", acBuffStr);
                JVRemoteListActivity.this.startActivity(intent);
            }

        }
    };

    @Override
    public void onHandler(int what, int arg1, int arg2, Object obj) {

        Log.e(TAG, "onHandler,what" + what + ";arg1=" + arg1 + ";arg2=" + arg2 + ";obj=" + obj);
        switch (what) {
            //连接结果,视频异常断开时关闭此界面
            case JVNetConst.CALL_CATEYE_CONNECTED: {
                if (arg2 != JVNetConst.CCONNECTTYPE_CONNOK) {
                    this.finish();
                }
                break;
            }
            //流媒体协议
            case JVNetConst.CALL_CATEYE_SENDDATA: {
                try {
                    com.alibaba.fastjson.JSONObject root = JSON.parseObject(obj.toString());
                    int nCmd = root.getInteger(AppConsts.TAG_NCMD);
                    int nPacketType = root.getInteger(AppConsts.TAG_NPACKETTYPE);
                    int result = root.getInteger(AppConsts.TAG_RESULT);
                    String reason = root.getString(AppConsts.TAG_REASON);
                    String dat = root.getString(AppConsts.TAG_DATA);
                    switch (nCmd) {
                        //检索视频文件
                        case JVNetConst.SRC_REMOTE_CHECK: {
                            switch (nPacketType) {
                                case JVNetConst.SRC_EX_CHECK_VIDEO:
                                    videoList = SovUtil.getStreamIPCFileList(dat, selectDateET.getText().toString());
                                    if (null != videoList && 0 != videoList.size()) {
                                        Collections.reverse(videoList);
                                        remoteVideoAdapter.setData(videoList);
                                        remoteLV.setAdapter(remoteVideoAdapter);
                                        remoteVideoAdapter.notifyDataSetChanged();
                                    } else {
                                        remoteVideoAdapter.setData(videoList);
                                        remoteVideoAdapter.notifyDataSetChanged();
                                        Toast.makeText(JVRemoteListActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                                    }
                                    break;
                            }
                            break;
                        }
                        case JVNetConst.SRC_REMOTE_DOWNLOAD:{
                            Log.e(TAG, "DOWNLOAD_FILE_SRC_REMOTE_DOWNLOAD,what" + what + ";arg1=" + arg1 + ";arg2=" + arg2 + ";obj=" + obj);
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            // 下载进度
            case JVNetConst.CALL_DOWNLOAD: {
                switch (arg2) {
                    //文件头回调
                    case JVNetConst.DT_FILE_HEAD: {
                        //file_length
                        Log.e(TAG, "DOWNLOAD_FILE-DT_FILE_HEAD:obj=" + obj.toString());
                        try {
                            com.alibaba.fastjson.JSONObject data = JSON.parseObject(obj.toString());
                            downLoadFileSize = data.getInteger("file_length");
                            downloadProTV.setText("开始下载-文件总大小：" + downLoadFileSize);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (downLoadFileSize <= 0) {
                            downLoadFileSize = 0;
                            downloadProTV.setText("下载失败：文件大小获取失败" + downLoadFileSize);
                            Toast.makeText(JVRemoteListActivity.this, "下载失败：文件大小获取失败", Toast.LENGTH_LONG).show();
                        }

                        break;
                    }
                    //文件数据回调
                    case JVNetConst.DT_FILE_DATA: {
                        Log.e(TAG, "DOWNLOAD_FILE-DT_FILE_DATA:arg1=" + arg1);

                        if (downLoadFileSize == 0) {
                            Toast.makeText(JVRemoteListActivity.this, "下载失败", Toast.LENGTH_LONG).show();
                            SovUtil.cancelStreamDownload(window);
                            break;
                        } else {
                            try {
                                com.alibaba.fastjson.JSONObject data = JSON.parseObject(obj.toString());
                                int dataLen = data.getInteger("data_len");
                                hasDownLoadSize += dataLen;
                                downloadProTV.setText("下载中-文件总大小：" + downLoadFileSize + "；已下载：" + hasDownLoadSize +"；进度："+ (int) ((float) hasDownLoadSize / downLoadFileSize * 100) + "%");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        break;
                    }
                    case JVNetConst.DT_FILE_TAIL: {
                        com.alibaba.fastjson.JSONObject data = JSON.parseObject(obj.toString());
                        int result = data.getInteger("result");

                        if(result == 1){
                            downloadProTV.setText("下载成功");
                            Toast.makeText(JVRemoteListActivity.this, "下载成功", Toast.LENGTH_LONG).show();
                        }else{
                            downloadProTV.setText("下载失败");
                            Toast.makeText(JVRemoteListActivity.this, "下载失败", Toast.LENGTH_LONG).show();
                        }

                        break;
                    }
                }
                break;
            }
            //下载按钮事件：录像下载
            case FLAG_DOWNLOAD_FILE: {
                StreamFile videoFile = videoList.get(arg1);
                String acBuffStr = videoFile.getFilePath();

                Log.v(TAG, "DOWNLOAD_FILE-acBuffStr:" + acBuffStr);
                String fileName = System.currentTimeMillis()
                        + AppConsts.VIDEO_MP4_KIND;
                String downFileFullName = AppConsts.DOWNLOAD_PATH + fileName;
                JniUtil.setDownloadFileName(window, downFileFullName);
                Log.e(TAG, "DOWNLOAD_FILE-downloadPath=" + downFileFullName);

                downLoadFileSize = 0;
                hasDownLoadSize = 0;
                SovUtil.startStreamDownload(window, acBuffStr);
                break;
            }
            default: {
                break;
            }
        }

    }

    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj) {
        handler.sendMessage(handler.obtainMessage(what, arg1, arg2, obj));

    }

    @Override
    protected void initSettings() {
        Intent intent = getIntent();
        if (null != intent) {
            window = intent.getIntExtra("window", 0);
        }
    }

    @Override
    protected void initUi() {
        setContentView(R.layout.activity_remotelist);
        ((TextView) findViewById(R.id.title_tv)).setText("远程回放");
        selectDateET = (EditText) findViewById(R.id.datetext);
        moreDataIV = (ImageView) findViewById(R.id.dateselectbtn);
        remoteVideoAdapter = new StreamRemoteVideoAdapter(JVRemoteListActivity.this);
        remoteLV = (ListView) findViewById(R.id.videolist);
        remoteLV.setOnItemClickListener(onItemClickListener);
        selectDateET.setInputType(InputType.TYPE_NULL);
        selectDateET.setOnTouchListener(onTouchListener);
        selectDateET.setText(String.format(AppConsts.FORMAT_DATE, year, month, day));
        moreDataIV.setOnTouchListener(onTouchListener);
        downloadProTV = (TextView) findViewById(R.id.download_process);
        year = rightNow.get(Calendar.YEAR);
        month = rightNow.get(Calendar.MONTH) + 1;
        day = rightNow.get(Calendar.DAY_OF_MONTH);
        selectDateET.setText(String.format(AppConsts.FORMAT_DATE, year, month, day));
        findViewById(R.id.ll_title_left_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        searchRemoteData();
    }

    /**
     * 取消下载
     *
     * @param view
     */
    public void cancelDownload(View view) {
        SovUtil.cancelStreamDownload(window);
    }

    /**
     * 查询文件列表
     *
     * @param view
     */
    public void searchFile(View view) {
        searchRemoteData();
    }

    /**
     * 检索远程回放数据
     */
    public void searchRemoteData() {
        String temStr = selectDateET.getText().toString();
        String[] temArray = temStr.split("-");
        year = Integer.parseInt(temArray[0]);
        month = Integer.parseInt(temArray[1]);
        day = Integer.parseInt(temArray[2]);

        SovUtil.checkStreamRemoteVideo(window, year, month, day);
    }

    @Override
    protected void saveSettings() {

    }

    @Override
    protected void freeMe() {

    }
}